<script setup lang="ts">
import { getCaptchaApi, loginByMobileApi } from "@/api/user";
import { useUserStore } from "@/store/user";
import { ref } from "vue";

defineOptions({
  options: {
    styleIsolation: "shared",
  },
});
//用户相关数据
const userStore = useUserStore()

//4.定义ref绑定给form
const formRef = ref<UniHelper.UniFormsInstance>();
// 1. 倒计时处理
const showCountDown = ref(false);

//1.声明校验数据
const formData = ref({
  mobile: "13230000047",
  code: "",
});

// 2.定义验证表单数据的规则
const formRules = {
  mobile: {
    rules: [
      { required: true, errorMessage: "请填写手机号码" },
      { pattern: /^1\d{10}$/, errorMessage: "手机号码格式不正确" },
    ],
  },
  code: {
    rules: [
      { required: true, errorMessage: "请输入验证码" },
      { pattern: /^\d{6}$/, errorMessage: "验证码格式不正确" },
    ],
  },
};

//获取验证码接口
const onShowCountDown = async () => {
  // 5. 校验手机号
  try {
    await formRef.value?.validateField!(["mobile"]);
  } catch (error) {
    uni.showToast({ title: "请输入正确的手机号码" });
  }
  showCountDown.value = true;
  const res = await getCaptchaApi({ mobile: formData.value.mobile, type: "login" });
  formData.value.code = res.code;
};

// 1.定义isAgree
const isAgree = ref(false);

//登入函数
const onsubmit = async () => {
  //校验手机和验证码
  await formRef.value?.validate!();
  if (!isAgree.value) {
    uni.showToast({ title: "请同意协议!" });
    return;
  }

  const res = await loginByMobileApi(formData.value);
    //持久化储存token
  userStore.token = res.token
  uni.showToast({ title: "登入成功!" });
  //跳转首页
  uni.switchTab({ url: "/pages/index/index" });
};
</script>

<template>
  <!-- 3.绑定表单校验规则 -->
  <uni-forms ref="formRef" v-model="formData" :rules="formRules" class="login-form">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        v-model="formData.code"
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text v-if="!showCountDown" class="text-button" @click="onShowCountDown"
        >获取验证码</text
      >
      <view class="text-button" v-else>
        <uni-countdown
          color="#16c2a3"
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="3"
          @timeup="showCountDown = false"
        />秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onsubmit">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
@import "../styles.scss";
</style>
